package com.xplay.xpocker.service.gaming.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xplay.xpocker.entity.GameRuRoomUser;
import com.xplay.xpocker.mapper.GameRuRoomUserMapper;
import com.xplay.xpocker.service.gaming.GameRuRoomUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xplay.xpocker.util.ObjectUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xplay
 * @since 2023-08-18
 */
@Service
public class GameRuRoomUserServiceImpl extends ServiceImpl<GameRuRoomUserMapper, GameRuRoomUser> implements GameRuRoomUserService {
    /**
     * 注意这里的玩家添加顺序 是按照房间人数递增
     * 如果出现有人退出
     * 那么应该重新清理数据,重新将玩家的序号 更新
     *
     * @param userId
     * @param roomId
     * @return
     */
    @Override
    public GameRuRoomUser addHome(BigDecimal userId, BigDecimal roomId) {
        LambdaQueryWrapper<GameRuRoomUser> exits = Wrappers.lambdaQuery(GameRuRoomUser.class).eq(GameRuRoomUser::getUserId, userId);
        List<GameRuRoomUser> users = list(exits);
        if (ObjectUtils.notEmpty(users)) {
            users.get(0).setOld(true);
            return users.get(0);
        }
        if (roomId == null) {
            return null;
        }
        LambdaQueryWrapper<GameRuRoomUser> allUserWrappers = Wrappers.lambdaQuery(GameRuRoomUser.class).eq(GameRuRoomUser::getRoomId, roomId);
        List<GameRuRoomUser> allUser = list(allUserWrappers);
        GameRuRoomUser roomUser = new GameRuRoomUser();
        roomUser.setRoomId(roomId);
        roomUser.setUserId(userId);
        roomUser.setSeq(allUser.size() + 1);
        save(roomUser);
        return roomUser;
    }

    @Override
    public void exitHome(BigDecimal userId, BigDecimal roomId) {
        remove(Wrappers.<GameRuRoomUser>lambdaQuery().eq(GameRuRoomUser::getUserId,userId)
                .eq(GameRuRoomUser::getRoomId,roomId));
    }

}
